<?

	include_once 'file.php';

	class Fmgr0v0r01_tgz extends Fmgr0v0r01_file{
		
		var $media_class = 'Archive';
		
		function is_gz(){
			return in_array($this->xtn(), array('gz', 'tgz'));
		}
		
		function is_tar(){
			return ($this->xtn() == 'tar');
		}

		function unpack(){
			$tmp = Cache::mktemp();
			$basename = $this->basename();
			$tmp_arch = "$tmp/$basename";
			$index = false;
			copy($this->realpath(), $tmp_arch);
			chdir($tmp);
			set_time_limit(0);
			ini_set('memory_limit', '24M');
			if($this->is_gz()) exec("gunzip \"$basename\"");
			// tenuous... but reliable
			foreach(glob("$tmp/*") as $tar_file) if(array_pop(explode('.', $tar_file)) == 'tar') break;
			
			// Work out which files are for appending by eliminating tars and gzs and dots now
			$scan_ignores = scandir($tmp);
			exec("tar -xvf \"$tar_file\"");
			if(is_file('smuoi_tarindex')){
				$index = @json_decode(file_get_contents('smuoi_tarindex'));
				if(is_object($index)){
					$index = new obj($index);
					$index->objectify();
					chdir('files');
					$scan_ignores = array('.', '..');
				}
			}
			if(!$index){
				foreach(scandir('./') as $file){
					if(in_array($file, $scan_ignores)) continue;
					$this->parent()->appendChild(realpath($file), 1);
				}
				return;
			}
			// now then...
			$id_index = new obj;
			$tmpl_index = new obj;
			$parent_tree = new obj;
			$parent_tree->set('/', $this->parent());
			foreach($index->index as $id=>$path){
				$set = $index->files->get($path);
				unset($set->id, $set->grp);
				$srcpath = realpath(".$path");
				$parent_path = ($p = strrpos($path, '/')) ? substr($path, 0, $p) : '/';
				$parent = $parent_tree->get($parent_path);
				if(is_dir($srcpath)){ 
					$new = $parent->mkdir(basename($srcpath), $set, 1);
					$parent_tree->set($path, $new);
				}else{
					$o = $this->pkg->build_file($srcpath, $set);	
					$new = $parent->appendChild($o, 1);
				}
				$id_index->set($id, $new);
				$tmpl_index->set($id, $set->get('tmpl'));
			}
			if($index->options->templates){
				foreach($tmpl_index as $id=>$tmpl){
					if(!$tmpl) continue;
					if(!$template = $id_index->get($tmpl)){
						error_log(print_r($tmpl, 1));
						continue;
					}
					$file = $id_index->get($id);
					$file->template = $template->id;
					$file->commit();
				}
			}
			$cache_path = Cache::subpath($tmp, 1);
			Cache::clearCache($cache_path, 0, 1);
			rmdir($tmp);
		}

	}

?>